# -*- coding: utf-8 -*-
"""
@Time: 2025/2/20 17:55
@File: login.py
@IDE: PyCharm
@Auth: Kendrick.Kc.Guan
@Email: 509556985@qq.com
@Version: 1.0
"""


import base64
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.permissions import AllowAny


class KcObtainAuthToken(ObtainAuthToken):
    authentication_classes = []  # 禁用所有认证类
    permission_classes = [AllowAny]  # 允许任意用户访问

    def post(self, request, *args, **kwargs):
        password_ = request.data.get('password')
        request.data['password'] = base64.b64decode(password_).decode('utf-8')
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            user = serializer.validated_data['user']
            token, created = Token.objects.get_or_create(user=user)
            return Response({'code': 200, 'msg': 'ok', 'token': token.key})
        except Exception as e:
            return Response({'code': 401, 'msg': '联系管理员'})



